/*
 * Copyright (c) 2023 bicntech
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * bicntech
 *
 */

package com.bicntech.common.utils.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;

/**
 * 图片工具类
 *
 * @author : JMY
 * @create 2023/7/14 13:58
 */
@Slf4j
public class ImgUtils {
    /**
     * 判断文件是否是图片
     */
    public static boolean isImage(MultipartFile file) {
        if (file.isEmpty()) {
            return false;
        }
        String fileType = FileUtil.getSuffix(file.getOriginalFilename());
        if (StrUtil.isBlank(fileType)) return false;
        if (Arrays.asList("JPG", "jpg", "png", "gif", "tif", "bmp", "jpeg").contains(fileType)) {
            return true;
        }

        BufferedImage image = null;
        try {
            // 如果是spring中MultipartFile类型，则代码如下
            image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
                return false;
            }
            return true;
        } catch (
                Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
